#include <sys/types.h>
#include <sys/stat.h>
//#include "./cmessageboxhint.h"
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <linux/input.h>

#include "threaddev.h"
#include <QDebug>

//---------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

#include <QCoreApplication>

#include <QDebug>
#include <poll.h>
#define D_BUZZER_MAX 3

ThreadDev::ThreadDev(QObject *parent) : QThread(parent)
{
    qDebug()<<" ThreadDev initial ";
    isBuzzerCount=false;
}

ThreadDev::~ThreadDev()
{
    close(buttons_fd);
}

void ThreadDev::setBuzzerPlay_slot()
{
    qDebug()<<"setBuzzerPlay_slot";
    isBuzzerCount=D_BUZZER_MAX;
}


//  new
int ThreadDev::key(void)
{
    int count;
    int fd;
    struct input_event ev_key;

    fd = open("/dev/event0", 0);	//根据实际情况 有可能不是
    if (fd < 0)
    {
        perror("open device key!");
        exit(1);
    }

    while (1)
    {
        count = read(fd, &ev_key, sizeof(struct input_event));

        if (EV_KEY == ev_key.type)
        {
//            //printf("ThreadDev ---  type:%d,code:%d,value:%d\n", ev_key.type, ev_key.code, ev_key.value);
//            if(m_pCustomInstace->m_pnAllFlagList[EM_AFT_LOCK_SCREEN_FLAGE] == EM_CF_ON || (m_pCustomInstace->m_pnAllFlagList[EM_AFT_TERMINATE_OVER_LAYER] == EM_CF_ON))
//            {
                emit sendKeySignal(ev_key.code, ev_key.value );
//            }
//            else
//            {
//                if(EM_CF_OFF == m_pCustomInstace->m_psMessageBoxInfo->nIsShowMessage)
//                {
//                    emit sendKeySignal(ev_key.code, ev_key.value );
//                }
//            }

        }
        if (EV_SYN == ev_key.type)
        {
            //printf("syn event\n");
        }

    }

    close(fd);

    return 0;

}
#define KEY_DEVICE_DIR "/dev/teachbox_key_read"
int ThreadDev::key_huatu_loop()
{

//    qDebug()<<"key_huatu_loop";
    int ret;
    struct pollfd fds[1];
    int bytes;
     unsigned int keyBuf[2];
     fds[0].fd     = keyFd;
     fds[0].events = POLLIN;

    ret = poll(fds, 1, 80);//timeout 80ms
    if (ret == 0)
         return 0;

    bytes = read(keyFd, (char*)keyBuf, sizeof(keyBuf));
    if(sizeof(keyBuf)!=bytes)
    {
         return 0;
     }
    char *pKey=new char[bytes];
    memcpy(pKey,keyBuf,bytes);
    key_sig_run(pKey,bytes);


}


void ThreadDev::key_sig_run(char* pBuf,unsigned int len)
{
    unsigned int *pKey;
    unsigned char flag;
    char temp[20];
   if(len<sizeof(unsigned int))
  {
        delete pBuf;
        return;
   }
    pKey=(unsigned int *)pBuf;
//      ui ->keyTextBrowser->clear();
      memset(temp,0,sizeof(temp));
     sprintf(temp,"k1:%08x",*pKey); //printf("k1:%x",);
     qDebug()<<"key1_____"<<temp;
//      ui ->keyTextBrowser->append(temp);

     if(0!=*pKey)
     {
         flag=LED_ON;//outputValue[0]|=TEACHBOX_BUZZER;

         emit sendKeySignal(*pKey, 1 );
         setBuzzerPlay_slot();
//         setLed_slot(TEACHBOX_BUZZER,flag);
     }
     else
     {

         flag=LED_OFF;// outputValue[0]&=~TEACHBOX_BUZZER;
         emit sendKeySignal(0, 0);
     }



       if(len>=sizeof(unsigned int)*2)
       {
              memset(temp,0,sizeof(temp));
             sprintf(temp,"k2:%08x",*(pKey+1)); //printf("k1:%x",);
//             ui ->keyTextBrowser->append(temp);
//             qDebug()<<"key2_____"<<temp;
        }
      delete pBuf;
}

void ThreadDev::setLed_slot(unsigned int led, unsigned char flag)
{
    if(flag)
      {
          outputValue[0]|=led;
          qDebug()<<"setLed on,led:"<<led;
      }
      else
      {
            qDebug()<<"setLed off,led:"<<led;
            outputValue[0]&=~led;
      }
      write(outputFd, (char*)outputValue, sizeof(unsigned int));
}


void ThreadDev::run()
{

//    key();
    initialLedOutput_huatu();
    initialKey_huatu();

    while(1)
    {
//        qDebug()<<"run loop";
        key_huatu_loop();
        buzzer_huatu_Loop();
//        msleep(50);
    }

    close(keyFd);

#if 0
    int ret;
    int i;
    char key_values[8];
    int keyval;

    struct input_event ev_key;

    static  unsigned int cnt = 0xff;// for count the times
   // int keyval;

    //open the buttons device
    if(( buttons_fd = open(BUTTONS_DEV, O_RDWR))<0 )
    {
        printf("Error opening %s",BUTTONS_DEV);
    }
    else
    {
        printf("open button devices ssuccessful\n");
    }

    forever{

        lock.lockForRead();
        read(buttons_fd, &ev_key, sizeof(struct input_event));

        emit sendKeySignal(ev_key.code, ev_key.value );

        lock.unlock();

    }
#endif
}

void ThreadDev::buzzer_huatu_Loop()
{
//    qDebug()<<"buzzer_huatu_Loop";
    if(isBuzzerCount>0)
    {
        if(D_BUZZER_MAX==isBuzzerCount)
        {
            setLed_slot(TEACHBOX_BUZZER,1);
        }
        isBuzzerCount--;
        if(0==isBuzzerCount)
        {
            setLed_slot(TEACHBOX_BUZZER,0);
        }
    }
}
#define OUTPUT_DEVICE_DIR "/dev/teachbox_Led_op"
void ThreadDev::initialLedOutput_huatu()
{
    //LED及其其他输出设备
    if((outputFd = open((char*)OUTPUT_DEVICE_DIR,O_RDWR)) == -1)
    {
//               ui->outputTextBrowser->insertPlainText(tr("LED及其其他输出设备启动            失败 "));
               perror("teachbox_Led_op Test Open Error: ");
               return;
    }
    setLed_slot(LED_ALL,LED_OFF);   //关闭所有输出
}

void ThreadDev::initialKey_huatu()
{
    if(-1==(keyFd = (open((char*)KEY_DEVICE_DIR,O_RDWR))) )
    {
           perror("teachbox_key_read Test Open Error: ");

    }
}

//多线程安全性测试专用
void ThreadDev::setMsg(QString msg)
{
    Msg = msg;
}
